import random

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from redis import Redis

from libs.captcha.captcha import captcha

from utils.smsutils import SmsUtil


# 图片验证码
class ImageCodeView(View):
    def get(self,request,uuid):
        print(uuid)
        #.1. 接收前端请求 uuid
        # 2. 生成验证码
        text, image = captcha.generate_captcha()
        # 以uuid为key  验证码为value  存到redis
        redis_conn = get_redis_connection('code')
        print('text=',text)
        # 添加到redis数据库，设置有效期 300秒
        redis_conn.setex(uuid,300,text)

        return HttpResponse(image,content_type='image/jpeg')


# 短信验证
class SmsView(View):

    def get(self,request,tem):
        # print(tem)

        # 如果手机号码为空  返回json数据  “手机号为空”
        if not tem:
            return JsonResponse({'code': 300, "errmsg": "手机号为空"})



        print('request',request.GET)
        # sms_codes / 19831803530 /?image_code = LN4W & image_code_id = ebb1ab89 - 344
        # d - 44
        # b9 - aaa0 - 91
        # b783e13ac13

        image_code:str = request.GET.get('image_code')

        image_code_uuid = request.GET.get('image_code_id')

        try:
            # 获取保存都在redis里的图片验证码
            redis: Redis = get_redis_connection('code')
            print(redis)
            image_code_redis = redis.get(image_code_uuid)
            if not image_code_redis:
                return JsonResponse({'code': 400, "errmsg": "验证码过期"})

            image_code_redis = image_code_redis.decode()

            if image_code.lower() != image_code_redis.lower():
                return JsonResponse({'code': 500, "errmsg": "图片验证码错了"})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 600, "errmsg": "网络异常"})

        flag_send = redis.get('flag_%s' % tem)
        # 如果存在返回提示信息
        if flag_send:
            return JsonResponse({'code':110, 'errmsg': '短信已经发送，请稍后再试'})
        print('发送短信给：',tem)
        # 不存在可以继续发送短信

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0,999999)

        print('code:',sms_code)

        SmsUtil().send_message(mobile=tem, code=sms_code)
        # send_sms_code.delay(tem, sms_code)

        # 1. 创建redis的管道 pipline 对象
        pl = redis.pipeline()
        # 2. 把redis的操作请求   添加到管道
        pl.setex('smscode_%s' % tem,60 * 3 ,sms_code)
        pl.setex('flag_%s' % tem, 60 , 1)
        # 3. 执行所有操作
        pl.execute()

        # redis.setex('smscode_%s' % tem,60 * 3 ,sms_code)
        # # 发送完  保存  key：flag_手机号   有效期60秒
        # redis.setex('flag_%s' % tem, 60 , 1)


        return  JsonResponse({'code':0,"errmsg":'ok'})